import random

import ddddocr
from DrissionPage import ChromiumPage

dp = ChromiumPage()

dp.get('https://cszg.mca.gov.cn/biz/ma/csmh/g/cszzsearch.html?value=社会', retry=3, interval=2, timeout=10)


def get_tracks(offset):
    """
    滑块的运动轨迹
       注意: 如果网站检测云加速生成轨迹, 则此方法可能无法正常工作
    """
    value = round(random.uniform(0.55, 0.75), 2)
    v, t, sum1 = 0, 0.3, 0
    plus = []
    mid = offset * value
    while sum1 < offset:
        if sum1 < mid:
            a = round(random.uniform(2.5, 3.5), 1)
        else:
            a = -round(random.uniform(2.0, 3.0), 1)
        s = v * t + 0.5 * a * (t ** 2)
        v = v + a * t
        sum1 += s
        plus.append(round(s))
    return plus


for i in range(5):  # 识别失败重试5次
    bg_img = dp.ele('#oriImg').src()
    cut_img = dp.ele('#cutImg').src()
    det = ddddocr.DdddOcr(det=False, ocr=False, show_ad=False)  # 关闭文字检测和文字识别和广告显示
    result = det.slide_match(cut_img, bg_img, simple_target=True)  # 简单模式
    print('滑块距离:', result)
    offset = result['target'][0]
    tracks = get_tracks(offset)
    print('滑块运动轨迹:', tracks)

    dp.actions.hold('#slider')
    for track in tracks:
        dp.actions.move(offset_x=track, offset_y=round(random.uniform(1.0, 3.0), 0), duration=0.1)

    dp.wait(1)
    dp.actions.release('#slider')
    dp.ele('#captchadiv').get_screenshot(path='captcha.png')  # 顺便截图验证

    dp.wait(2)
    if '验证' in dp.ele('.path_content').text:
        print('滑动失败, 刷新滑块...')
        dp.ele('x://img[@onclick="getSlideCaptcha()"]').click()
    else:
        print('滑动成功, 继续下一步...')
        break

# 获取元素
for tr in dp.eles('x://tr')[1:]:
    tds = [td.text.strip() for td in tr.eles('x://td')]
    print(tds)



